package com.jming.tenement.webapi.config;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;
import com.google.gson.JsonSerializer;
import com.google.gson.LongSerializationPolicy;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.spring.web.json.Json;

import java.util.List;

/**
 * @author jming
 */
@Configuration
public class MvcConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/*")
                .addResourceLocations("classpath:/static/",
                        "classpath:/META-INF/resources/webjars/",
                        "classpath:/META-INF/resources/");

        // 解决 SWAGGER2 404报错
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");

    }

    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        GsonBuilder gb = new GsonBuilder();
        gb.enableComplexMapKeySerialization();
        gb.setDateFormat("yyyy-MM-dd HH:mm:ss");
        gb.setLongSerializationPolicy(LongSerializationPolicy.STRING);
        gb.serializeNulls();
        gb.registerTypeAdapter(Json.class, (JsonSerializer<Json>) (json, type, jsonSerializationContext) ->
                JsonParser.parseString(json.value()));
        GsonHttpMessageConverter gson = new GsonHttpMessageConverter();
        gson.setGson(gb.create());
        converters.add(gson);

        super.configureMessageConverters(converters);
    }
}
